package sudoku.server.persistencia.sqlserver;

import java.rmi.RemoteException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import sudoku.server.dominio.Tablero;
import sudoku.server.persistencia.TableroDAO;

public class TableroDAOSQLServer extends TableroDAO {

	public TableroDAOSQLServer(Tablero tablero) {
		super(tablero);
	}

	@Override
	public void getTablero(String id) throws Exception {
		String SQL="Select Numeros from Sudoku where Id=?";
		PreparedStatement p=Agente.getAgente().getDB().prepareStatement(SQL);
		p.setInt(1, Integer.parseInt(id));
		ResultSet r=p.executeQuery();
		if (r.next()) {
			this.tablero.setId(Integer.parseInt(id));
			String ristra=r.getString(1);
			this.tablero.setNumeros(ristra);
		}
		this.tablero.crearVectorDeJugadores();
		p.close();

	}

	@Override
	public void insert(String ristra) throws Exception {
		String SQL="Insert into Sudoku (Numeros) values (?)";
		PreparedStatement p=Agente.getAgente().getDB().prepareStatement(SQL);
		p.setString(1, this.tablero.getRistra());
		p.executeUpdate();
		p.close();
	}

	@Override
	public void update() throws Exception {
		String SQL="Update Sudoku set Numeros=? where Id=?";
		try {
			PreparedStatement p=Agente.getAgente().getDB().prepareStatement(SQL);
			p.setString(1, this.tablero.getRistra());
			p.setInt(2, this.tablero.getId());
			p.executeUpdate();
			p.close();
		} catch (SQLException e) {
			throw new RemoteException(e.toString());
		}			
	}

	@Override
	public Vector<String> getTableros(String tipo) throws Exception {
        Vector<String> result=new Vector<String>();
        String SQL="Select Id from Sudoku";
        PreparedStatement p=Agente.getAgente().getDB().prepareStatement(SQL);
        ResultSet r=p.executeQuery();
        while (r.next()) {
            result.add(new String(""+r.getInt(1)));
        }
        p.close();
        return result;
	}
}